import time, json
import hashlib
from tencentcloud.live.v20180801 import models
from tencentcloud.trtc.v20190722 import models as trtc_models
from lib.live.abstract_live import AbstractLive
import logging
app_logger = logging.getLogger("student")
import traceback


class LiveServers(AbstractLive):

    def dropLiveStrem(self, streamname):
        """
        断开直播流(当某些原因暂停主播继续推流时)
        :param streamname: 流名称
        :return:
        """
        try:
            client = self._method()
            req = models.DropLiveStreamRequest()
            params = {
                "AppName": "live",
                "DomainName": self.push_url,
                "StreamName": streamname
            }
            req.from_json_string(json.dumps(params))
            resp = client.DropLiveStream(req)
            return resp.to_json_string()
        except:
            return False

    def resumeLiveStream(self, streamname):
        """
        恢复直播推流
        :param streamname: 流名称
        :return:
        """
        try:
            client = self._method()
            req = models.ResumeLiveStreamRequest()
            params = {
                "AppName": "live",
                "DomainName": self.push_url,
                "StreamName": streamname
            }
            req.from_json_string(json.dumps(params))
            resp = client.ResumeLiveStream(req)
            return resp.to_json_string()
        except:
            return False

    def forbidLiveStream(self, streamname):
        """
        禁推直播流
        :param streamname: 流名称
        :return:
        """
        try:
            client = self._method()
            req = models.ForbidLiveStreamRequest()
            params = {
                "AppName": "live",
                "DomainName": self.push_url,
                "StreamName": streamname,
                # "ResumeTime": "11"
            }
            req.from_json_string(json.dumps(params))
            resp = client.ForbidLiveStream(req)
            return resp.to_json_string()
        except:
            return False

    def createLiveRecordTemplate(self, templatename, vodfilename):
        """
        创建录制模板 (直播)
        :param templatename:
        :return:{
                  "Response": {
                    "RequestId": "3c140219-cfe9-470e-b241-907877d6fb03"
                  }
                }
        """
        try:
            client = self._method()
            req = models.CreateLiveRecordTemplateRequest()
            params = {
                "TemplateName": templatename,
                "Description": "直播录制",
                "Mp4Param": {
                    # "RecordInterval": 1,
                    "StorageTime": 0,
                    "Enable": 1,
                    # "VodSubAppId": 1,
                    "VodFileName": vodfilename,
                    "Procedure": "1",
                    "StorageMode": "normal",
                    "ClassId": 828173
                }
            }
            req.from_json_string(json.dumps(params))
            resp = client.CreateLiveRecordTemplate(req)
            return resp.to_json_string()
        except:
            return False

    def createLiveRecordRule(self, streamname, templateid):
        """
        创建录制规则 (直播)
        :param streamname: 流名称
        :param templateid: 模板id
        :return:
        """
        try:
            client = self._method()
            req = models.CreateLiveRecordRuleRequest()
            params = {
                "DomainName": self.push_url,
                "AppName": "live",
                "StreamName": str(streamname),
                "TemplateId": templateid,
            }
            req.from_json_string(json.dumps(params))
            resp = client.CreateLiveRecordRule(req)
            return resp.to_json_string()
        except:
            return False

    def getTxSecret(self, key, livecode, str_time):
        """
        防盗链的key
        :param livecode:
        :param str_time:
        :return:
        """
        struck_time = time.strptime(str_time, "%Y-%m-%d %H:%M:%S")
        unix_time = int(time.mktime(struck_time))
        txTime = hex(unix_time)[2:].upper()
        tx = hashlib.md5()
        tx.update((key + str(livecode) + txTime).encode(encoding='utf-8'))
        return tx.hexdigest(), txTime

    def getPushUrl(self, livecode, is_key=None, str_time=None):
        """
        生成推流地址
        :param key:
        :param str_time:
        :return:
        """
        pushUrl = self.push_url
        if is_key and str_time:
            txSecret, txTime = self.getTxSecret(self.PushKey, livecode, str_time)
            PushUrls = [
                {'obs': ['rtmp://{}/live/'.format(pushUrl), '{}?txSecret={}&txTime={}'.format(livecode, txSecret, txTime)]},
                {'udp': ['webrtc://{}/live/{}?txSecret={}&txTime={}'.format(pushUrl, livecode, txSecret, txTime)]}
            ]
            return PushUrls
        else:
            PushUrls = [
                {'obs': 'rtmp://{}/live/{}'.format(pushUrl, livecode)}
            ]
            return PushUrls

    def getPlayUrl(self, livecode, str_time):
        """
        生成播放地址
        :return:
        """
        playUrl = self.play_url
        txSecret, txTime = self.getTxSecret(self.PlayKey, livecode, str_time)
        PlayUrls = {
            'rtmp': 'rtmp://{}/live/{}?txSecret={}&txTime={}'.format(playUrl, livecode, txSecret, txTime),
            'flv': 'http://{}/live/{}.flv?txSecret={}&txTime={}'.format(playUrl, livecode, txSecret, txTime),
            'hls': 'http://{}/live/{}.m3u8?txSecret={}&txTime={}'.format(playUrl, livecode, txSecret, txTime),
            'udp': 'webrtc://{}/live/{}?txSecret={}&txTime={}'.format(playUrl, livecode, txSecret, txTime)
        }
        return PlayUrls

    def removeUser(self, userids, roomid):
        """
        移出用户 (实时音视频trtc， 非字符串房间号)
        :param userids: 用户id
        :param roomid: 房间号
        :return:
        """
        try:
            client = self._trtc_method()
            req = trtc_models.RemoveUserRequest()
            params = {
                "SdkAppId": self.AppId,
                "RoomId": roomid,
                "UserIds": userids  # [ "dwdw", "fvdf" ]
            }
            req.from_json_string(json.dumps(params))
            resp = client.RemoveUser(req)
            return resp.to_json_string()
        except:
            return False

    def getStreamPlayInfoList(self, StartTime, EndTime, StreamName):
        """
        查询流的播放信息列表
        @param StartTime: 开始时间
        @param EndTime: 结束时间
        @param StreamName: 流名称
        @return:
        """
        try:
            client = self._method()
            req = models.DescribeStreamPlayInfoListRequest()
            params = {
                'StartTime': StartTime,
                'EndTime': EndTime,
                'StreamName': str(StreamName)
            }
            req.from_json_string(json.dumps(params))
            resp = client.DescribeStreamPlayInfoList(req)
            return json.loads(resp.to_json_string())
        except:
            return False

    def getTrtcUserList(self, StartTime, EndTime, CommId, UserIds, PageNumber=0, PageSize=100):
        """
        trtc获取用户历史列表
        :param StartTime:
        :param EndTime:
        :param CommId:
        :return:
        """
        try:
            client = self._trtc_method()
            req = trtc_models.DescribeUserInformationRequest()
            params = {
                "StartTime": StartTime,
                "EndTime": EndTime,
                "SdkAppId": str(self.AppId),
                "PageNumber": str(PageNumber),
                "PageSize": str(PageSize),
                "UserIds": UserIds,
                "CommId": str(CommId)
            }
            req.from_json_string(json.dumps(params))
            resp = client.DescribeUserInformation(req)
            return json.loads(resp.to_json_string())
        except:
            err = traceback.format_exc()
            app_logger.error(err)
            return False

    def getRoomInfoForCommId(self, StartTime, EndTime, RoomId, PageNumber=0, PageSize=100):
        """
        trtc获取历史房间
        :param StartTime:
        :param EndTime:
        :param RoomId:
        :return:
        """
        try:
            client = self._trtc_method()
            req = trtc_models.DescribeRoomInformationRequest()
            params = {
                "StartTime": StartTime,
                "EndTime": EndTime,
                "SdkAppId": str(self.AppId),
                "RoomId": str(RoomId),
            }
            req.from_json_string(json.dumps(params))
            resp = client.DescribeRoomInformation(req)
            return json.loads(resp.to_json_string())
        except:
            err = traceback.format_exc()
            app_logger.error(err)
            return False

    def dismissRoomByStrRoomId(self, RoomId):
        """
        解散trtc房间
        @param RoomId:
        @return:
        """
        try:
            client = self._trtc_method()
            req = trtc_models.DismissRoomRequest()
            params = {
                "SdkAppId": self.AppId,
                "RoomId": RoomId,
            }
            req.from_json_string(json.dumps(params))
            resp = client.DismissRoom(req)
            return json.loads(resp.to_json_string())
        except:
            err = traceback.format_exc()
            app_logger.error(err)
            return False